package com.lg.algorithm.ms;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

public class Deadlock {
    static class  myThread extends  Thread{
        Object lock1;
        Object lock2;
        CountDownLatch countDownLatch;
        myThread(Object lock1,Object lock2, CountDownLatch countDownLatch) {
            this.lock1 = lock1;
            this.lock2 = lock2;
            this.countDownLatch = countDownLatch;
        }
        @SneakyThrows
        @Override
        public void run() {
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + " 拿到锁 " + lock1);
                countDownLatch.countDown();
                countDownLatch.await();
                System.out.println(Thread.currentThread().getName() + " 开始拿锁 " + lock1);
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + " 拿到锁 " + lock1);
                }
            }
        }
    }

    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        myThread myThread1 = new myThread(lock1, lock2, countDownLatch);
        myThread myThread2 = new myThread(lock2, lock1, countDownLatch);
        myThread1.start();
        myThread2.start();
        System.out.println("main over");
    }


}
